package jfae.core.properties.parsers;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.util.ArrayList;
import java.util.List;

/**
 * 
 * @author bobpuley
 *
 * @param <T>
 */
public class ClassParser<T> {

	/**
	 * 
	 */
	protected List<PropertyHandler<T>> handlers;
	
	/**
	 * 
	 * @param handlers
	 */
	public ClassParser(List<PropertyHandler<T>> handlers) {
		this.handlers = handlers;
	}
	
	/**
	 * 
	 * @param type
	 * @return
	 */
	public List<T> parse(Class<?> type){
		List<T> result = new ArrayList<T>();
		try {
			BeanInfo beanInfo = Introspector.getBeanInfo(type);
			PropertyDescriptor[] props = beanInfo.getPropertyDescriptors();
			for (PropertyDescriptor prop : props) {
				try {
					T parsed = handleProperty(prop, beanInfo);
					if (parsed != null){
						result.add(parsed);
					}
				} catch (StopParsing s) {
					break;
				}
				
			}
		} catch (IntrospectionException e) {
			// TODO Auto-generated catch block
			// propagare l'eccezione
			e.printStackTrace();
		}
		return result;
	}

	private T handleProperty(PropertyDescriptor prop, BeanInfo beanInfo) {
		T parsed = null;
		for (PropertyHandler<T> handler : handlers) {
			if(handler.accept(prop, beanInfo)){
				parsed = handler.parse(prop);
				if(parsed != null){
					break;
				}
			}
		}
		return parsed;
	}

	public static class StopParsing extends RuntimeException{

		private static final long serialVersionUID = 1L;
		
		private StopParsing() {
			super();
		}

		public static void stop(){
			throw new StopParsing();
		}
		
	}
}
